package com.lwk.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.lwk.domain.Student;
import com.lwk.service.StudentService;
import com.lwk.utils.PageBean;
import com.opensymphony.xwork2.ModelDriven;

import net.sf.json.JSONObject;

public class StudentAction implements ModelDriven<Student> {
    private Student student = new Student();
    private StudentService studentService;

    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    @Override
    public Student getModel() {
        return student;
    }

    // 接收分页的数据：
    // 接收当前页数和每页显示的记录数，这两个值在easyUI中已经有规定。page当前页数，rows每页显示记录数
    private Integer page;
    private Integer rows;

    // 查询所有学生
    public String list() throws Exception {
        // 封装离线查询对象
        DetachedCriteria dc = DetachedCriteria.forClass(Student.class);
        // 判断并封装参数
        if (student.getStudentNumber() != null && student.getStudentNumber().trim().length() > 0) {
            dc.add(Restrictions.eq("studentNumber", student.getStudentNumber()));
        }
        if (student.getCollege() != null && student.getCollege().trim().length() > 0) {
            dc.add(Restrictions.eq("college", student.getCollege()));
        }
        if (student.getMajor() != null && student.getMajor().trim().length() > 0) {
            dc.add(Restrictions.eq("major", student.getMajor()));
        }
        if (student.getClassAndGrade() != null && student.getClassAndGrade().trim().length() > 0) {
            dc.add(Restrictions.eq("classAndGrade", student.getClassAndGrade()));
        }
        if (student.getYear() != null && student.getYear().trim().length() > 0) {
            dc.add(Restrictions.eq("year", student.getYear()));
        }
        if (student.getPtc() != null && student.getPtc() == 0) {
            dc.add(Restrictions.lt("ptc", 6));
        }
        if (student.getPtc() != null && student.getPtc() == 1) {
            dc.add(Restrictions.ge("ptc", 6));
        }
        System.out.println(student.getCollege());
        /*
         * if(StringUtils.isNotBlank(Student.getCust_name())){
		 * dc.add(Restrictions.like("cust_name", "%"+Student.getCust_name()+"%")); }
		 */

        // 1 调用Service查询分页数据(PageBean)
        PageBean pb = studentService.getPageBean(dc, page, rows);
        // 2 将PageBean放入request域,转发到列表页面显示
        // ActionContext.getContext().put("pageBean", pb);

        // ----------对象StudentList生成JSON
        // JsonConfig config = new JsonConfig();
        // 设置生成json时不包含哪些字段
        // 使用jsonlib或者fastjson
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", pb.getTotalCount());
        map.put("rows", pb.getList());
        System.out.println(map);

        // JSONArray,JSONObject
        JSONObject jsonObject = JSONObject.fromObject(map);

		/*
		 * config.setExcludes(new String[]{"Student","saleVisits"}); String json =
		 * JSONArray.fromObject(pb.getList()).toString(); System.out.println(json);
		 */

        ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
        ServletActionContext.getResponse().getWriter().write(jsonObject.toString());
        return "none";
    }

    // 根据id删除学生
    public String delete() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        try {
            // 调用业务层:
            Student student1 = studentService.getById(student.getSid());
            System.out.println(student1);
            studentService.delete(student1);
            map.put("msg", "删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "删除失败!");
        }
        // 将map转成JSON:
        JSONObject jsonObject = JSONObject.fromObject(map);
        System.out.println(jsonObject.toString());
        ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
        ServletActionContext.getResponse().getWriter().println(jsonObject.toString());// {"msg":..}
        return null;
    }

    // 根据id查找学生
    public String getById() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        // 调用业务层:
        Student student1 = studentService.getById(student.getSid());
        System.out.println(student1);
        map.put("studentName", student1.getStudentName());
        map.put("sid", student1.getSid().toString());
        map.put("studentNumber", student1.getStudentNumber());
        map.put("password", student1.getPassword());
        map.put("ptc", student1.getPtc().toString());
        map.put("classAndGrade", student1.getClassAndGrade());
        map.put("college", student1.getCollege());
        map.put("major", student1.getMajor());
        map.put("year", student1.getYear());
        // 将map转成JSON:
        JSONObject jsonObject = JSONObject.fromObject(map);
        System.out.println(jsonObject.toString());
        ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
        ServletActionContext.getResponse().getWriter().println(jsonObject.toString());// {"msg":..}
        return null;
    }

    // 根据studentNumber查找学生
	/*
	 * public String getByStudentNumber() throws Exception { Map<String,
	 * List<Student>> map = new HashMap<String, List<Student>>(); // 封装离线查询对象
	 * System.out.println(student); DetachedCriteria dc =
	 * DetachedCriteria.forClass(Student.class); if (student.getStudentNumber() !=
	 * null && student.getStudentNumber().trim().length() > 0) {
	 * dc.add(Restrictions.eq("studentNumber", student.getStudentNumber())); } //
	 * 调用业务层: List<Student> list = studentService.getByStudentNumber(dc);
	 * map.put("list", list); // 将map转成JSON: JSONObject jsonObject =
	 * JSONObject.fromObject(map);
	 *
	 * return jsonObject.toString(); }
	 */

    // 保存学生
    public String saveOrUpdate() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        try {
            // 调用业务层:
            studentService.saveOrUpdate(student);
            map.put("msg", "操作成功!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "操作失败!");
        }
        // 将map转成JSON:
        JSONObject jsonObject = JSONObject.fromObject(map);
        System.out.println(jsonObject.toString());
        ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
        ServletActionContext.getResponse().getWriter().println(jsonObject.toString());// {"msg":..}
        return null;
    }

    /**
     * 导出excel文件
     */
    public void export() {

        // 封装离线查询对象
        DetachedCriteria dc = DetachedCriteria.forClass(Student.class);
        // 判断并封装参数
        if (student.getStudentNumber() != null && student.getStudentNumber().trim().length() > 0) {
            dc.add(Restrictions.eq("studentNumber", student.getStudentNumber()));
        }
        if (student.getCollege() != null && student.getCollege().trim().length() > 0) {
            dc.add(Restrictions.eq("college", student.getCollege()));
        }
        if (student.getMajor() != null && student.getMajor().trim().length() > 0) {
            dc.add(Restrictions.eq("major", student.getMajor()));
        }
        if (student.getClassAndGrade() != null && student.getClassAndGrade().trim().length() > 0) {
            dc.add(Restrictions.eq("classAndGrade", student.getClassAndGrade()));
        }
        if (student.getYear() != null && student.getYear().trim().length() > 0) {
            dc.add(Restrictions.eq("year", student.getYear()));
        }
        if (student.getPtc() != null && student.getPtc() == 0) {
            dc.add(Restrictions.lt("ptc", 6));
        }
        if (student.getPtc() != null && student.getPtc() == 1) {
            dc.add(Restrictions.ge("ptc", 6));
        }
        // 表名
        String filename = "学生成绩.xls";
        HttpServletResponse response = ServletActionContext.getResponse();
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(filename.getBytes(), "ISO-8859-1"));// 中文名称进行转码
            // 调用导出业务
            studentService.export(response.getOutputStream(), dc);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入excel文件
     */
    private File file;// 上传的文件
    private String fileFileName;// 上传的文件名称

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    private String fileContentType;// 上传的文件类型

    /**
     * 导入数据
     */
    public void doImport() {
        Map<String, String> map = new HashMap<String, String>();
        // 文件类型判断
        if (!"application/vnd.ms-excel".equals(fileContentType)) {
            map.put("msg", "上传的文件必须为excel文件!");
            //ajaxReturn(false, "上传的文件必须为excel文件");
            // 将map转成JSON:
            JSONObject jsonObject = JSONObject.fromObject(map);
            System.out.println(jsonObject.toString());
            ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
            try {
                ServletActionContext.getResponse().getWriter().println(jsonObject.toString());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }// {"msg":..}
        }
        try {
            studentService.doImport(new FileInputStream(file));
            map.put("msg", "上传的文件成功");
            //ajaxReturn(true, "上传的文件成功");
            // 将map转成JSON:
            JSONObject jsonObject = JSONObject.fromObject(map);
            System.out.println(jsonObject.toString());
            ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
            ServletActionContext.getResponse().getWriter().println(jsonObject.toString());// {"msg":..}
        } catch (IOException e) {
            map.put("msg", "上传的文件失败!");
            //ajaxReturn(false, "上传的文件失败");
            // 将map转成JSON:
            JSONObject jsonObject = JSONObject.fromObject(map);
            System.out.println(jsonObject.toString());
            ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
            try {
                ServletActionContext.getResponse().getWriter().println(jsonObject.toString());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }// {"msg":..}
            e.printStackTrace();
        }
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }
}
